package com.ywu.boot.handler;

import com.ywu.boot.config.BootConfigAppConfig;
import com.ywu.boot.exception.YwuRuntimeException;
import com.ywu.common.constant.CommonConstant;
import com.ywu.common.result.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName YwuGlobalException
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/3/3 21:13
 * @Version 1.0
 **/
@RestController
@ControllerAdvice
@Slf4j
public class YwuGlobalExceptionHandler {

    @Autowired
    private BootConfigAppConfig appConfig;

    @ExceptionHandler(YwuRuntimeException.class)
    public CommonResult<Object> handleYwuGlobalException(YwuRuntimeException e) {
        if (appConfig.getFullExceptionLog()) {
            log.error("ywu runtime exception error: {}", e);
        } else {
            log.error("ywu runtime exception error: {}", e.getMessage());
        }
        return CommonResult.error().setCode(CommonConstant.SERVICE_ERROR_CODE)
                .setErrorCode("ywu runtime exception error")
                .setMessage(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public CommonResult<Object> handleException(Exception e) {
        if (appConfig.getFullExceptionLog()) {
            log.error("ywu exception error: {}", e);
        } else {
            log.error("ywu exception error: {}", e.getMessage());
        }
        return CommonResult.error().setCode(CommonConstant.SERVICE_ERROR_CODE)
                .setErrorCode("ywu exception error")
                .setMessage(e.getMessage());
    }
}
